package com.mrdeer.uaa.service;

import com.alibaba.fastjson.JSON;
import com.mrdeer.uaa.api.OAuthClientDetailsService;
import com.mrdeer.uaa.api.entity.OAuthClientDetails;
import com.mrdeer.uaa.common.WebUtils;
import com.mrdeer.uaa.repository.OAuthRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：xie jianchu
 * @date ：Created in 2020/9/4 0004 16:56
 */
@Slf4j
@Service
public class OAuthClientDetailsServiceImpl implements OAuthClientDetailsService {
    @Autowired
    private OAuthRepository oAuthRepository;

    @Override
    public void createClientDetails(Map map) {
        log.info("OAuthClientDetailsServiceImpl createClientDetails map:{}", map);
        OAuthClientDetails clientDetails = new OAuthClientDetails()
                .clientId(map.get("clientId").toString())
                .clientSecret(map.get("clientSecret").toString())
                .resourceIds("iot-resource")
                .authorities("client_credentials,password,authorization_code,implicit,refresh_token")
                .scope("read")
                .webServerRedirectUri(null)
                .authorities("ROLE_API")
                .accessTokenValidity(7200)
                .refreshTokenValidity(259200)
                .additionalInformation(null)
                .createTime(LocalDateTime.now())
                .archived(false)
                .trusted(false);
        oAuthRepository.saveOAuthClientDetails(clientDetails);
        log.info("()|Save OAuthClientDetails:{}", WebUtils.getIp(), clientDetails);
    }

    @Override
    public Map getClientDetailsByClientId(String appId) {
        OAuthClientDetails oAuthClientDetails = oAuthRepository.findOAuthClientDetails(appId);
        log.info("getClientDetailsByClientId param appId:{} ret:{}", appId, JSON.toJSONString(oAuthClientDetails));
        Map map = new HashMap();
        map.put("client_id", oAuthClientDetails.clientId());
        map.put("client_secret", oAuthClientDetails.clientSecret());
        return map;
    }
}
